<?php

namespace app\index\controller;

use app\BaseController;
use think\facade\Cache;
use app\index\validate\WechartValidate;
use think\facade\Request as faRequest;
use app\index\model\UserModel;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
class Wechat extends BaseController
{
    private $appid = "wx193599a4ded7a235";
    private $appSecret = "1523a5349225b4f07f9bea5f61e9c477";
    public function index()
    {
        $sql = new UserModel();
        $info = $sql->where('openid', input('openid'))->findOrEmpty();
        if ($info->isEmpty()) {
            return result()->fail("该账号不存在", 400);
        }
        return result()->success($info);
    }
    public function autoLogin() {
        $params = faRequest::post(['code']);
        $validate = new WechartValidate();
        if (!$validate->scene('login')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appSecret}&js_code={$params['code']}&grant_type=authorization_code";
        $result = json_decode(file_get_contents($url), true);
        if (isset($result['errcode'])) {
            return result()->fail($result['errmsg'], $result['errcode']);
        }
        $sql = new UserModel();
        $info = $sql->where('openid', $result['openid'])->findOrEmpty();
        if ($info->isEmpty()) {
            return result()->success($result, '获取openid');
        }
        $payload = array(
            "iat" => time(), // 签发时间
            "ext" => strtotime("7 day"), // 过期时间
            "data"=> ['id' => "USER:".$info['id']]  // 携带数据
        );
        $token = JWT::encode($payload, config('app.jwt.secret'), config('app.jwt.algo'));
        return result()->success([
            'token' => $token
        ], '登录成功');
    }

    public function doRegister() {
        $params = faRequest::post(['loginCode', 'phoneCode', 'superiorUserId']);
        $validate = new WechartValidate();
        if (!$validate->scene('register')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        //  获取openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appSecret}&js_code={$params['loginCode']}&grant_type=authorization_code";
        $result = json_decode(file_get_contents($url), true);
        if (isset($result['errcode'])) {
            return result()->fail($result['errmsg'], $result['errcode']);
        }
        $sql = new UserModel();
        $info = $sql->where('openid', $result['openid'])->findOrEmpty();
        if (!$info->isEmpty()) {
            return result()->fail("账号已存在", 400);
        }
        //  获取手机号
        $client = new Client([
            'verify' => false
        ]);
        $response = $client->post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$this->getAccessToken()}", [
            'json' => [
                'code' => $params['phoneCode']
            ]
        ]);
        $content = $response->getBody()->getContents();
        $res = json_decode($content, true);
        if($res['errcode'] !== 0) {
            return result()->fail($res['errmsg'], $res['errcode']);
        }
        $sql->nickName = $res['phone_info']['phoneNumber'];
        $sql->cellphone = $res['phone_info']['phoneNumber'];
        $sql->openid = $result['openid'];
        if(isset($params['superiorUserId']) && $params['superiorUserId']) {
            $sql->superiorUserId = $params['superiorUserId'];
        }
        $sql->save();
        $payload = array(
            "iat" => time(), // 签发时间
            "ext" => strtotime("7 day"), // 过期时间
            "data"=> ['id' => "USER:".$sql['id']]  // 携带数据
        );
        $token = JWT::encode($payload, config('app.jwt.secret'), config('app.jwt.algo'));
        return result()->success([
            'token' => $token
        ], '注册成功');
    }

    public function getAccessToken()
    {
        $accessToken = Cache::get('wechat_access_token');
        if (!$accessToken) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appSecret}";
            $result = json_decode(file_get_contents($url), true);

            if (isset($result['access_token'])) {
                Cache::set('wechat_access_token', $result['access_token'], 7200);
                $accessToken = $result['access_token'];
            } else {
                return '获取access_token失败';
            }
        }
        return $accessToken;
    }
}
